<!DOCTYPE html>


<html lang="zh-CN">


<head>
  <meta charset="utf-8" />
    
  <meta name="description" content="杰克小麻雀的博客" />
  
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    用Python实现一个软件自动升级系统 |  半亩方塘
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">

  
<link rel="stylesheet" href="/css/custom.css">

  
  
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

  
  

  

</head>

</html>
<body>
  <div id="app">
    
      
      <canvas width="1777" height="841"
        style="position: fixed; left: 0px; top: 0px; z-index: 99999; pointer-events: none;"></canvas>
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-用Python实现一个软件自动升级系统"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  用Python实现一个软件自动升级系统
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/2020/04/25/%E7%94%A8Python%E5%AE%9E%E7%8E%B0%E4%B8%80%E4%B8%AA%E8%BD%AF%E4%BB%B6%E8%87%AA%E5%8A%A8%E5%8D%87%E7%BA%A7%E7%B3%BB%E7%BB%9F/" class="article-date">
  <time datetime="2020-04-26T06:26:49.000Z" itemprop="datePublished">2020-04-25</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/Python/">Python</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">3.6k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">16 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <blockquote>
<p>作者: 杰克小麻雀<br>原文链接: <a target="_blank" rel="noopener" href="https://blog.csdn.net/yushuaigee/article/details/105140425">https://blog.csdn.net/yushuaigee/article/details/105140425</a></p>
</blockquote>
<p><strong>目录</strong></p>
<ul>
<li><p><a href="#%E4%B8%80%E3%80%81%E6%9C%8D%E5%8A%A1%E7%AB%AF">一、服务端</a></p>
<ul>
<li><input disabled="" type="checkbox"> <a href="#1.%C2%A0XML%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6">1. XML配置文件</a></li>
<li><input disabled="" type="checkbox"> <a href="#%C2%A02.%C2%A0%E6%9C%8D%E5%8A%A1%E7%AB%AF%E4%BB%A3%E7%A0%81%E8%AE%BE%E8%AE%A1"> 2. 服务端代码设计</a></li>
</ul>
</li>
<li><p><a href="#%E4%BA%8C%E3%80%81%E5%AE%A2%E6%88%B7%E7%AB%AF">二、客户端</a></p>
<ul>
<li><input disabled="" type="checkbox"> <a href="#1.%C2%A0XML%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6">1. XML配置文件</a></li>
<li><input disabled="" type="checkbox"> <a href="#2.%20%E5%AE%A2%E6%88%B7%E7%AB%AF%E4%BB%A3%E7%A0%81%E8%AE%BE%E8%AE%A1">2. 客户端代码设计</a></li>
</ul>
</li>
<li><p><a href="#%E4%B8%89%E3%80%81%E8%BF%90%E8%A1%8C%E6%95%88%E6%9E%9C">三、运行效果</a></p>
<ul>
<li><input disabled="" type="checkbox"> <a href="#1.%20%E7%A8%8B%E5%BA%8F%E7%9B%AE%E5%BD%95%E7%BB%93%E6%9E%84">1. 程序目录结构</a></li>
<li><input disabled="" type="checkbox"> <a href="#2.%20%E6%9C%8D%E5%8A%A1%E7%AB%AF%E8%BF%90%E8%A1%8C%E6%95%88%E6%9E%9C">2. 服务端运行效果</a></li>
<li><input disabled="" type="checkbox"> <a href="#3.%20%E5%AE%A2%E6%88%B7%E7%AB%AF%E8%BF%90%E8%A1%8C%E6%95%88%E6%9E%9C">3. 客户端运行效果</a></li>
</ul>
</li>
<li><p><a href="#%E5%9B%9B%E3%80%81%E6%94%B9%E8%BF%9B%E6%80%9D%E8%B7%AF">四、改进思路</a></p>
</li>
<li><p><a href="#%E4%BA%94%E3%80%81%E6%96%87%E4%BB%B6%E4%B8%8B%E8%BD%BD">五、文件下载</a></p>
</li>
</ul>
<p>软件客户端在发布新版本的时候，有时候只修改了几个文件，没必要让用户重新下载整个客户端再重新安装，同时也不应要求用户每次去手动下载更新的文件，再手动覆盖本地文件。这个时候需要设计一个自动升级机制，在某些条件触发时(比如软件启动的时候)自动查看是否有更新，如果有就将改变的内容下载下来，更新本地旧文件，再根据情况判断是否重启客户端。这个功能现在是桌面程序必备的功能，基本所有的客户端都有这个检查更新的功能。我曾经用Python实现过一个基于http下载的简易自动升级系统，可以独立运行、复用在不同的情景下。</p>
<p>设计思路很简单：当有新版本需要发布时，将文件放在服务端，生成一个记录每个文件变化的配置文件。客户端本地也有一个记录文件信息的配置文件，客户端检查更新时，将服务端的配置文件下载下来，与本地配置文件进行比较，然后下载有变化的文件，覆盖本地文件（如果文件正在使用中，可能无法覆盖，这时候更新前应该先关闭正在运行的客户端），中间有Tkinter做的界面提示更新进度。更新结束后根据策略决定是否重启客户端。</p>
<h2 id="一、服务端"><a href="#一、服务端" class="headerlink" title="一、服务端"></a>一、服务端</h2><p>服务端要做的事，首先是选择一个端口号，开启用于响应客户端下载的http服务。然后把指定的目录下的所有文件都扫描一遍，给每个文件记录一个版本号和最后修改日期，再生成一个总版本号，写在XML配置文件里。</p>
<p>比如版本号从0开始，第一次发布程序时，每个文件的版本号都是0，总版本号也是0，第二次发布时，扫描每个文件的最后修改日期，如果日期大于XML文件中记录的日期，将这个文件的记录日期更新，版本号加1。扫描完毕，只要有任意文件的版本号发生变化，总版本号也加1。这样客户端在检查更新时，只需要先比较服务端的总版本号和自己本地的总版本号是否一致。如果不一致，再下载XML文件比较每一个文件版本号变化，如果一致就不用下载XML文件比较了（可以在服务端增加一个接口，客户端请求这个接口时返回一个总版本号字段）。</p>
<h3 id="1-XML配置文件"><a href="#1-XML配置文件" class="headerlink" title="1. XML配置文件"></a>1. <strong>XML</strong>配置文件</h3><p><strong>1.1 XML配置文件结构</strong></p>
<p>ServerInfo节点：记录服务端IP和端口号，可以让客户端知道去哪里下载，当下载地址或端口号变化时，通过更新这个节点，客户端下次更新时就会到新的地址和端口号下载。</p>
<p>ClientVersion节点：要升级的模块的文件信息，包含1个总版本号属性，子节点包括该模块下每个文件的相对路径、文件大小、最后更新时间和版本号。这个节点可以设计多个，用不同的节点名，区分不同的模块，每个模块都有自己的总版本号。这里以1个模块为例。</p>
<p><strong>1.2 XML配置文件示例：</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 处理xml的类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">VersionInfoXml</span>():</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, xml_path, server_info=<span class="literal">None</span>, module_list=<span class="literal">None</span></span>):</span></span><br><span class="line">        self.xml_path = xml_path</span><br><span class="line">        <span class="keyword">if</span> server_info <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">            <span class="keyword">if</span> module_list <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">                module_list = [<span class="string">&quot;ClientVersion&quot;</span>]</span><br><span class="line">            self.create_new_xml(server_info, module_list)</span><br><span class="line">        self.tree = ET.parse(self.xml_path)</span><br><span class="line">        self.root = self.tree.getroot()</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">create_new_xml</span>(<span class="params">self, server_info, module_info</span>):</span></span><br><span class="line">        root = ET.Element(<span class="string">&quot;versionInfo&quot;</span>)</span><br><span class="line">        ServerInfo = ET.SubElement(root, <span class="string">&quot;ServerInfo&quot;</span>)</span><br><span class="line">        ET.SubElement(ServerInfo, <span class="string">&quot;ServerIp&quot;</span>).text = server_info[<span class="number">0</span>]</span><br><span class="line">        ET.SubElement(ServerInfo, <span class="string">&quot;ServerPort&quot;</span>).text = server_info[<span class="number">1</span>]</span><br><span class="line">        ET.SubElement(ServerInfo, <span class="string">&quot;XmlLocalPath&quot;</span>).text = server_info[<span class="number">2</span>]</span><br><span class="line">        <span class="keyword">for</span> each_module <span class="keyword">in</span> module_info:</span><br><span class="line">            ET.SubElement(root, each_module).<span class="built_in">set</span>(<span class="string">&quot;Version&quot;</span>, <span class="string">&quot;0&quot;</span>)</span><br><span class="line">        self.save_change(root)</span><br><span class="line">        print(<span class="string">&quot;I created a new temp xml!&quot;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">save_change</span>(<span class="params">self, root=<span class="literal">None</span></span>):</span></span><br><span class="line">        <span class="keyword">if</span> root <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">            root = self.root</span><br><span class="line">        rough_bytes = ET.tostring(root, <span class="string">&quot;utf-8&quot;</span>)</span><br><span class="line">        rough_string = <span class="built_in">str</span>(rough_bytes, encoding=<span class="string">&quot;utf-8&quot;</span>).replace(<span class="string">&quot;\n&quot;</span>, <span class="string">&quot;&quot;</span>).replace(<span class="string">&quot;\t&quot;</span>, <span class="string">&quot;&quot;</span>).replace(<span class="string">&quot;    &quot;</span>, <span class="string">&quot;&quot;</span>)</span><br><span class="line">        content = minidom.parseString(rough_string)</span><br><span class="line">        <span class="keyword">with</span> <span class="built_in">open</span>(self.xml_path, <span class="string">&#x27;w+&#x27;</span>) <span class="keyword">as</span> fs:</span><br><span class="line">            content.writexml(fs, indent=<span class="string">&quot;&quot;</span>, addindent=<span class="string">&quot;\t&quot;</span>, newl=<span class="string">&quot;\n&quot;</span>, encoding=<span class="string">&quot;utf-8&quot;</span>)</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">changeServerInfo</span>(<span class="params">self, name, value</span>):</span></span><br><span class="line">        <span class="keyword">if</span> <span class="built_in">type</span>(value) <span class="keyword">is</span> <span class="built_in">int</span>:</span><br><span class="line">            value = <span class="built_in">str</span>(value)</span><br><span class="line">        Xpath = <span class="string">&quot;ServerInfo/%s&quot;</span> % name</span><br><span class="line">        element = self.root.find(Xpath)</span><br><span class="line">        <span class="keyword">if</span> element <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">            element.text = value</span><br><span class="line">            <span class="comment"># self.save_change()</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            print(<span class="string">&quot;I can&#x27;t find \&quot;ServerInfo/%s\&quot; in xml!&quot;</span> % name)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">addObject</span>(<span class="params">self, module_name, file_path, file_size, last_update_time, version</span>):</span></span><br><span class="line">        moduleVersion = self.root.find(module_name)</span><br><span class="line">        <span class="built_in">object</span> = ET.SubElement(moduleVersion, <span class="string">&quot;object&quot;</span>)</span><br><span class="line">        ET.SubElement(<span class="built_in">object</span>, <span class="string">&quot;FileRelativePath&quot;</span>).text = <span class="built_in">str</span>(file_path)</span><br><span class="line">        ET.SubElement(<span class="built_in">object</span>, <span class="string">&quot;FileSize&quot;</span>).text = <span class="built_in">str</span>(file_size)</span><br><span class="line">        ET.SubElement(<span class="built_in">object</span>, <span class="string">&quot;LastUpdateTime&quot;</span>).text = <span class="built_in">str</span>(last_update_time)</span><br><span class="line">        ET.SubElement(<span class="built_in">object</span>, <span class="string">&quot;Version&quot;</span>).text = <span class="built_in">str</span>(version)</span><br><span class="line">        <span class="comment"># self.save_change()</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">deleteObject</span>(<span class="params">self, module_name, file_name</span>):</span></span><br><span class="line">        Xpath = <span class="string">&quot;%s/object&quot;</span> % module_name</span><br><span class="line">        objects = self.root.findall(Xpath)</span><br><span class="line">        moudleVersion = self.root.find(module_name)</span><br><span class="line">        <span class="keyword">for</span> element <span class="keyword">in</span> objects:</span><br><span class="line">            <span class="keyword">if</span> element.find(<span class="string">&#x27;FileRelativePath&#x27;</span>).text == file_name:</span><br><span class="line">                moudleVersion.remove(element)</span><br><span class="line">                <span class="comment"># self.save_change()</span></span><br><span class="line">                print(<span class="string">&quot;Delete object: %s&quot;</span> % file_name)</span><br><span class="line">                <span class="keyword">break</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            print(<span class="string">&quot;I can&#x27;t find \&quot;%s\&quot; in xml!&quot;</span> % file_name)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">updateObject</span>(<span class="params">self, module_name, file_name, version</span>):</span></span><br><span class="line">        <span class="keyword">if</span> <span class="built_in">type</span>(version) <span class="keyword">is</span> <span class="built_in">int</span>:</span><br><span class="line">            version = <span class="built_in">str</span>(version)</span><br><span class="line">        Xpath = <span class="string">&quot;%s/object&quot;</span> % module_name</span><br><span class="line">        objects = self.root.findall(Xpath)</span><br><span class="line">        <span class="keyword">for</span> element <span class="keyword">in</span> objects:</span><br><span class="line">            <span class="keyword">if</span> element.find(<span class="string">&#x27;FileRelativePath&#x27;</span>).text == file_name:</span><br><span class="line">                element.find(<span class="string">&#x27;Version&#x27;</span>).text = version</span><br><span class="line">                <span class="comment"># self.save_change()</span></span><br><span class="line">                <span class="comment"># print(&quot;Update \&quot;%s\&quot; version: %s&quot; % (file_name, version))</span></span><br><span class="line">                <span class="keyword">break</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            print(<span class="string">&quot;I can&#x27;t find \&quot;%s\&quot; in xml!&quot;</span> % file_name)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">updateAttribute</span>(<span class="params">self, module_name, version</span>):</span></span><br><span class="line">        <span class="keyword">if</span> <span class="built_in">type</span>(version) <span class="keyword">is</span> <span class="built_in">int</span>:</span><br><span class="line">            version = <span class="built_in">str</span>(version)</span><br><span class="line">        moduleVersion = self.root.find(module_name)</span><br><span class="line">        moduleVersion.<span class="built_in">set</span>(<span class="string">&quot;Version&quot;</span>, version)</span><br><span class="line">        <span class="comment"># self.save_change()</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getObjects</span>(<span class="params">self, module_name</span>):</span></span><br><span class="line">        list_element = []</span><br><span class="line">        Xpath = <span class="string">&quot;%s/object&quot;</span> % module_name</span><br><span class="line">        objects = self.root.findall(Xpath)</span><br><span class="line">        <span class="keyword">for</span> element <span class="keyword">in</span> objects:</span><br><span class="line">            dict_element = &#123;&#125;</span><br><span class="line">            <span class="keyword">for</span> key, value <span class="keyword">in</span> <span class="built_in">enumerate</span>(element):</span><br><span class="line">                dict_element[value.tag] = value.text</span><br><span class="line">            list_element.append(dict_element)</span><br><span class="line">        <span class="keyword">return</span> list_element</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">addModule</span>(<span class="params">self, module</span>):</span></span><br><span class="line">        self.root.append(module)</span><br><span class="line">        <span class="comment"># self.save_change()</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">deleteModule</span>(<span class="params">self, module_name</span>):</span></span><br><span class="line">        module = self.root.find(module_name)</span><br><span class="line">        <span class="keyword">if</span> module <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">            self.root.remove(module)</span><br><span class="line">            <span class="comment"># self.save_change()</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getModules</span>(<span class="params">self</span>):</span></span><br><span class="line">        dict_element = &#123;&#125;</span><br><span class="line">        objects = self.root.getchildren()</span><br><span class="line">        <span class="keyword">for</span> key, value <span class="keyword">in</span> <span class="built_in">enumerate</span>(objects):</span><br><span class="line">            dict_element[value.tag] = value.attrib.get(<span class="string">&quot;Version&quot;</span>)</span><br><span class="line">        <span class="keyword">del</span> dict_element[<span class="string">&quot;ServerInfo&quot;</span>]</span><br><span class="line">        <span class="keyword">return</span> dict_element</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getAttribute</span>(<span class="params">self, module_name</span>):</span></span><br><span class="line">        moduleVersion = self.root.find(module_name)</span><br><span class="line">        <span class="keyword">return</span> moduleVersion.get(<span class="string">&quot;Version&quot;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get_node_value</span>(<span class="params">self, path</span>):</span></span><br><span class="line">        <span class="string">&#x27;&#x27;&#x27;查找某个路径匹配的第一个节点</span></span><br><span class="line"><span class="string">           tree: xml树</span></span><br><span class="line"><span class="string">           path: 节点路径&#x27;&#x27;&#x27;</span></span><br><span class="line">        node = self.tree.find(path)</span><br><span class="line">        <span class="keyword">if</span> node == <span class="literal">None</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">None</span></span><br><span class="line">        <span class="keyword">return</span> node.text</span><br></pre></td></tr></table></figure>
<h3 id="2-服务端代码设计"><a href="#2-服务端代码设计" class="headerlink" title="2. 服务端代码设计"></a>2. <strong>服务端代码设计</strong></h3><p>源码文件太长，这里只贴出主要的两个方法，具体实现源码文件放在文末下载。</p>
<p>首先是根扫描所有文件，生成一个最新xml配置文件，然后再比较两个xml，分析出增删改。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># -*- coding: utf-8 -*-</span></span><br><span class="line"><span class="comment"># @Time    : 2019/4/25 20:16</span></span><br><span class="line"><span class="comment"># @Author  : yushuaige</span></span><br><span class="line"><span class="comment"># @File    : AutoCheckVersion.py</span></span><br><span class="line"><span class="comment"># @Software: PyCharm</span></span><br><span class="line"><span class="comment"># @Function: 实现客户端自动更新（服务端）</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 处理xml的类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">VersionInfoXml</span>():</span></span><br><span class="line">    <span class="keyword">pass</span> <span class="comment"># 同上面xml类</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">AutoCheckVersion</span>(<span class="params">old_xml_path, new_xml_path</span>):</span></span><br><span class="line">    <span class="string">&#x27;&#x27;&#x27;</span></span><br><span class="line"><span class="string">    比较两个xml的objects节点，分析出增加，更改，和删除的文件列表，并在新xml里更新版本号</span></span><br><span class="line"><span class="string">    :param old_xml: 旧xml的完整路径</span></span><br><span class="line"><span class="string">    :param new_xml: 新xml的完整路径</span></span><br><span class="line"><span class="string">    :return: len(add_list), len(delete_list), len(change_list),</span></span><br><span class="line"><span class="string">    :return: add_list: [filname1, filname2], delete_list: [filname1, filname2] change_list: [filname1, filname2]</span></span><br><span class="line"><span class="string">    &#x27;&#x27;&#x27;</span></span><br><span class="line">    print(<span class="string">&quot;Analyze the xml files and update the version number ...&quot;</span>)</span><br><span class="line">    old_xml = VersionInfoXml(old_xml_path)</span><br><span class="line">    new_xml = VersionInfoXml(new_xml_path)</span><br><span class="line">    <span class="comment"># 先分析模块的增、删、改</span></span><br><span class="line">    old_modules = <span class="built_in">list</span>(old_xml.getModules().keys())</span><br><span class="line">    new_modules = <span class="built_in">list</span>(new_xml.getModules().keys())</span><br><span class="line">    add_modules_list = <span class="built_in">list</span>(<span class="built_in">set</span>(new_modules).difference(<span class="built_in">set</span>(old_modules)))</span><br><span class="line">    <span class="keyword">for</span> module_name <span class="keyword">in</span> add_modules_list:</span><br><span class="line">        ET.SubElement(old_xml.root, module_name).<span class="built_in">set</span>(<span class="string">&quot;Version&quot;</span>, <span class="number">0</span>)</span><br><span class="line">    common_modules_list = [item <span class="keyword">for</span> item <span class="keyword">in</span> old_modules <span class="keyword">if</span> item <span class="keyword">in</span> new_modules]</span><br><span class="line">    <span class="comment"># 分析每个的模块中的每个文件的增、删、改</span></span><br><span class="line">    total_add_list = []</span><br><span class="line">    total_delete_list = []</span><br><span class="line">    total_change_list = []</span><br><span class="line">    common_modules_list.extend(add_modules_list)</span><br><span class="line">    <span class="keyword">for</span> module_name <span class="keyword">in</span> common_modules_list:</span><br><span class="line">        old_xml_objects = old_xml.getObjects(module_name)</span><br><span class="line">        new_xml_objects = new_xml.getObjects(module_name)</span><br><span class="line">        old_xml_objects_dict = &#123;file_info[<span class="string">&quot;FileRelativePath&quot;</span>]: file_info <span class="keyword">for</span> file_info <span class="keyword">in</span> old_xml_objects&#125;</span><br><span class="line">        new_xml_objects_dict = &#123;file_info[<span class="string">&quot;FileRelativePath&quot;</span>]: file_info <span class="keyword">for</span> file_info <span class="keyword">in</span> new_xml_objects&#125;</span><br><span class="line">        old_data_list = <span class="built_in">set</span>(old_xml_objects_dict.keys())</span><br><span class="line">        new_data_list = <span class="built_in">set</span>(new_xml_objects_dict.keys())</span><br><span class="line">        add_list = <span class="built_in">list</span>(new_data_list.difference(old_data_list))</span><br><span class="line">        delete_list = <span class="built_in">list</span>(old_data_list.difference(new_data_list))</span><br><span class="line">        common_list = <span class="built_in">list</span>(old_data_list.intersection(new_data_list))</span><br><span class="line">        change_list = []</span><br><span class="line">        <span class="comment"># 更新每个文件的版本号信息</span></span><br><span class="line">        <span class="keyword">for</span> file_name <span class="keyword">in</span> common_list:</span><br><span class="line">            new_version = <span class="built_in">int</span>(old_xml_objects_dict[file_name][<span class="string">&quot;Version&quot;</span>])</span><br><span class="line">            update = TimeFormatComp(new_xml_objects_dict[file_name][<span class="string">&quot;LastUpdateTime&quot;</span>],</span><br><span class="line">                                    old_xml_objects_dict[file_name][<span class="string">&quot;LastUpdateTime&quot;</span>])</span><br><span class="line">            <span class="keyword">if</span> update <span class="keyword">is</span> <span class="literal">True</span>:</span><br><span class="line">                change_list.append(file_name)</span><br><span class="line">                new_version += <span class="number">1</span></span><br><span class="line">            new_xml.updateObject(module_name, file_name, new_version)</span><br><span class="line">        <span class="comment"># 更新模块版本信息</span></span><br><span class="line">        new_module_version = <span class="built_in">int</span>(old_xml.getAttribute(module_name))</span><br><span class="line">        <span class="keyword">if</span> <span class="built_in">len</span>(add_list) <span class="keyword">or</span> <span class="built_in">len</span>(delete_list) <span class="keyword">or</span> <span class="built_in">len</span>(change_list):</span><br><span class="line">            new_module_version = new_module_version + <span class="number">1</span></span><br><span class="line">        new_xml.updateAttribute(module_name, new_module_version)</span><br><span class="line"></span><br><span class="line">        total_add_list.extend(add_list)</span><br><span class="line">        total_delete_list.extend(delete_list)</span><br><span class="line">        total_change_list.extend(change_list)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 保存到文件</span></span><br><span class="line">    new_xml.save_change()</span><br><span class="line">    print(<span class="string">&quot;Analysis update info done. Save the new xml ...&quot;</span>)</span><br><span class="line">    <span class="comment"># 结果提示</span></span><br><span class="line">    <span class="keyword">if</span> <span class="built_in">len</span>(total_add_list) <span class="keyword">or</span> <span class="built_in">len</span>(total_delete_list) <span class="keyword">or</span> <span class="built_in">len</span>(total_change_list):</span><br><span class="line">        <span class="comment"># 替换旧的xml文件</span></span><br><span class="line">        os.remove(old_xml_path)</span><br><span class="line">        os.rename(new_xml_path, old_xml_path)</span><br><span class="line">        print(<span class="string">&quot;Done. add: %d, delete: %d, update: %d. The new client version: %s.&quot;</span> % (</span><br><span class="line">            <span class="built_in">len</span>(total_add_list), <span class="built_in">len</span>(total_delete_list), <span class="built_in">len</span>(total_change_list), <span class="built_in">str</span>(new_xml.getModules())))</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        os.remove(new_xml_path)</span><br><span class="line">        print(<span class="string">&quot;No file changed! The current client version: %s.&quot;</span> % (<span class="built_in">str</span>(new_xml.getModules())))</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">len</span>(total_add_list), <span class="built_in">len</span>(total_delete_list), <span class="built_in">len</span>(total_change_list)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">CreateNewXmlFromFiles</span>(<span class="params">client_dir</span>):</span></span><br><span class="line">    <span class="string">&#x27;&#x27;&#x27;</span></span><br><span class="line"><span class="string">    遍历文件夹所有文件，生成标准xml</span></span><br><span class="line"><span class="string">    :param client_dir: 要遍历的文件夹路径</span></span><br><span class="line"><span class="string">    :return: 生成的xml的完整路径</span></span><br><span class="line"><span class="string">    &#x27;&#x27;&#x27;</span></span><br><span class="line">    print(<span class="string">&quot;Scan the folder and create the temp xml file ...&quot;</span>)</span><br><span class="line">    config_parser = configparser.ConfigParser()</span><br><span class="line">    config_parser.read(os.path.dirname(sys.path[<span class="number">0</span>]) + <span class="string">&#x27;\\cfg.ini&#x27;</span>)</span><br><span class="line">    UPDATE_HOST = config_parser.get(<span class="string">&quot;mqtt&quot;</span>, <span class="string">&#x27;serv&#x27;</span>)</span><br><span class="line">    server_info = [UPDATE_HOST, <span class="string">&quot;8888&quot;</span>, <span class="string">&quot;dev_manage_win&quot;</span>]</span><br><span class="line">    module_list = os.listdir(client_dir)</span><br><span class="line">    new_xml = VersionInfoXml(<span class="string">&quot;VersionInfoTemp.xml&quot;</span>, server_info, module_list)</span><br><span class="line">    <span class="keyword">for</span> module_name <span class="keyword">in</span> module_list:</span><br><span class="line">        module_dir = os.path.join(client_dir, module_name)</span><br><span class="line">        <span class="keyword">for</span> (dirpath, dirnames, filenames) <span class="keyword">in</span> os.walk(module_dir):</span><br><span class="line">            <span class="keyword">for</span> file <span class="keyword">in</span> filenames:</span><br><span class="line">                file_dir = os.path.join(dirpath, file)</span><br><span class="line">                file_path = file_dir.replace(client_dir, <span class="string">&quot;&quot;</span>).strip(<span class="string">&quot;\\&quot;</span>).replace(<span class="string">&quot;\\&quot;</span>, <span class="string">&quot;/&quot;</span>)</span><br><span class="line">                file_size = os.path.getsize(file_dir)</span><br><span class="line">                last_update_time = TimeStampFormat(os.path.getmtime(file_dir))</span><br><span class="line">                version = <span class="number">1</span></span><br><span class="line">                new_xml.addObject(module_name, file_path, file_size, last_update_time, version)</span><br><span class="line">    new_xml.save_change()</span><br><span class="line">    new_xml_path = os.path.join(sys.path[<span class="number">0</span>], <span class="string">&quot;VersionInfoTemp.xml&quot;</span>)</span><br><span class="line">    <span class="keyword">return</span> new_xml_path</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h2 id="二、客户端"><a href="#二、客户端" class="headerlink" title="二、客户端"></a>二、客户端</h2><h3 id="1-XML配置文件-1"><a href="#1-XML配置文件-1" class="headerlink" title="1. XML配置文件"></a>1. <strong>XML</strong>配置文件</h3><p>为了简便，客户端和服务端处理xml文件的类用同一个。</p>
<h3 id="2-客户端代码设计"><a href="#2-客户端代码设计" class="headerlink" title="2. 客户端代码设计"></a>2. 客户<strong>端代码设计</strong></h3><p>源码文件太长，这里只贴出主要的两个方法，具体实现源码文件放在文末下载。</p>
<p>下载最新xml配置文件和本地配置文件进行比较，然后分析出增删改，进行下载和删除。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># -*- coding: utf-8 -*-</span></span><br><span class="line"><span class="comment"># @Time    : 2019/4/25 20:16</span></span><br><span class="line"><span class="comment"># @Author  : yushuaige</span></span><br><span class="line"><span class="comment"># @File    : AutoUpdate.py</span></span><br><span class="line"><span class="comment"># @Software: PyCharm</span></span><br><span class="line"><span class="comment"># @Function: 实现客户端自动更新（客户端）</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 处理xml的类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">VersionInfoXml</span>:</span></span><br><span class="line">    <span class="keyword">pass</span> <span class="comment"># 同上面xml类</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 手动更新时，检查更新</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">CheckUpdate</span>(<span class="params">server_ip, server_port, module_name, order</span>):</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 主要函数</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">AutoUpdate</span>(<span class="params">server_ip, server_port, module_name, order</span>):</span></span><br><span class="line">    time_start = time.perf_counter()</span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        download_url = <span class="string">&quot;http://&#123;0&#125;:&#123;1&#125;/&#123;2&#125;&quot;</span>.<span class="built_in">format</span>(server_ip, server_port, <span class="string">&quot;VersionInfo.xml&quot;</span>)</span><br><span class="line">        local_path = os.path.join(sys.path[<span class="number">0</span>], <span class="string">&quot;VersionInfoTemp.xml&quot;</span>)</span><br><span class="line">        print(<span class="string">&quot;download_url: &quot;</span> + download_url)</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> download_file_by_http(download_url, local_path):</span><br><span class="line">            <span class="keyword">raise</span> Exception()</span><br><span class="line">    <span class="keyword">except</span> Exception <span class="keyword">as</span> e:</span><br><span class="line">        <span class="comment"># tkinter.messagebox.showerror(&quot;更新无法继续&quot;, &quot;获取最新版本列表文件出现异常！&quot;)</span></span><br><span class="line">        print(<span class="string">&quot;Update error: Can&#x27;t get the latest VersionInfo xml!&quot;</span>)</span><br><span class="line">        <span class="comment"># root.destroy()</span></span><br><span class="line">        <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">    root.update()</span><br><span class="line">    root.deiconify()</span><br><span class="line">    <span class="comment"># 比较文件变化</span></span><br><span class="line">    add_dict, delete_list = analyze_update_info(local_xml_path, update_xml_path, module_name)</span><br><span class="line">    <span class="keyword">if</span> add_dict == &#123;&#125; <span class="keyword">and</span> delete_list == []:</span><br><span class="line">        os.remove(update_xml_path)</span><br><span class="line">        <span class="comment"># tkinter.messagebox.showinfo(&quot;更新无法继续&quot;, &quot;当前客户端已经是最新版本！&quot;)</span></span><br><span class="line">        print(<span class="string">&quot;No file changed!&quot;</span>)</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">    <span class="comment"># 下载需要更新的文件</span></span><br><span class="line">    download_progress(add_dict)</span><br><span class="line">    <span class="comment"># 文件覆盖到主目录</span></span><br><span class="line">    prompt_info11.<span class="built_in">set</span>(<span class="string">&quot;正在解压...&quot;</span>)</span><br><span class="line">    prompt_info13.<span class="built_in">set</span>(<span class="string">&quot;总体进度：99.9%&quot;</span>)</span><br><span class="line">    prompt_info21.<span class="built_in">set</span>(<span class="string">&quot;&quot;</span>)</span><br><span class="line">    root.update()</span><br><span class="line">    source_dir = os.path.join(sys.path[<span class="number">0</span>], <span class="string">&quot;TempFolder&quot;</span>)</span><br><span class="line">    dest_dir = os.path.dirname(sys.path[<span class="number">0</span>])</span><br><span class="line">    <span class="comment"># dest_dir = os.path.join(sys.path[0], &quot;test_main&quot;)</span></span><br><span class="line">    override_dir(source_dir, dest_dir)</span><br><span class="line">    <span class="comment"># 删除要删除的文件</span></span><br><span class="line">    <span class="keyword">for</span> file <span class="keyword">in</span> delete_list:</span><br><span class="line">        delete_dir(os.path.join(dest_dir, file))</span><br><span class="line">    <span class="comment"># 更新xml文件</span></span><br><span class="line">    <span class="keyword">if</span> module_name == <span class="string">&quot;all_module&quot;</span>:</span><br><span class="line">        os.remove(local_xml_path)</span><br><span class="line">        os.rename(update_xml_path, local_xml_path)</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        update_xml(local_xml_path, update_xml_path, module_name)</span><br><span class="line">    <span class="comment"># 客户端更新结束</span></span><br><span class="line">    time_end = time.perf_counter()</span><br><span class="line">    print(<span class="string">&quot;更新耗时：%ds&quot;</span> % (time_end - time_start))</span><br><span class="line">    prompt_info11.<span class="built_in">set</span>(<span class="string">&quot;更新完毕。&quot;</span>)</span><br><span class="line">    prompt_info13.<span class="built_in">set</span>(<span class="string">&quot;总体进度：100.0%&quot;</span>)</span><br><span class="line">    root.update()</span><br><span class="line">    <span class="comment"># tkinter.messagebox.showinfo(&quot;更新完成&quot;, &quot;更新完毕，耗时：%ds&quot; % (time_end - time_start))</span></span><br><span class="line">    <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 分析两个xml文件</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">analyze_update_info</span>(<span class="params">local_xml, update_xml, module_name</span>):</span></span><br><span class="line">    <span class="string">&#x27;&#x27;&#x27;</span></span><br><span class="line"><span class="string">    分析本地xml文件和最新xml文件获得增加的文件和要删除的文件</span></span><br><span class="line"><span class="string">    :param local_xml: 本地xml文件路径</span></span><br><span class="line"><span class="string">    :param update_xml: 下载的最新xml文件路径</span></span><br><span class="line"><span class="string">    :return: download_info: &#123;filename1: fizesize1, filename2: fizesize2&#125;, delete_list: [filname1, filname2]</span></span><br><span class="line"><span class="string">    &#x27;&#x27;&#x27;</span></span><br><span class="line">    print(<span class="string">&quot;Analyze the xml files and check the version number ...&quot;</span>)</span><br><span class="line">    old_xml = VersionInfoXml(local_xml)</span><br><span class="line">    new_xml = VersionInfoXml(update_xml)</span><br><span class="line">    module_names = []</span><br><span class="line">    <span class="keyword">if</span> module_name == <span class="string">&quot;all_module&quot;</span>:</span><br><span class="line">        module_names = new_xml.getModules()</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        module_names.append(module_name)</span><br><span class="line">    download_info_total = &#123;&#125;</span><br><span class="line">    delete_list_total = []</span><br><span class="line">    <span class="keyword">for</span> module_name <span class="keyword">in</span> module_names:</span><br><span class="line">        <span class="keyword">if</span> old_xml.getAttribute(module_name) <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">            ET.SubElement(old_xml.root, module_name).<span class="built_in">set</span>(<span class="string">&quot;Version&quot;</span>, <span class="string">&quot;0&quot;</span>)</span><br><span class="line">        <span class="keyword">if</span> new_xml.getAttribute(module_name) &amp;lt;= old_xml.getAttribute(module_name):</span><br><span class="line">            <span class="keyword">continue</span></span><br><span class="line">        old_xml_objects = old_xml.getObjects(module_name)</span><br><span class="line">        new_xml_objects = new_xml.getObjects(module_name)</span><br><span class="line">        old_xml_objects_dict = &#123;file_info[<span class="string">&quot;FileRelativePath&quot;</span>]: file_info <span class="keyword">for</span> file_info <span class="keyword">in</span> old_xml_objects&#125;</span><br><span class="line">        new_xml_objects_dict = &#123;file_info[<span class="string">&quot;FileRelativePath&quot;</span>]: file_info <span class="keyword">for</span> file_info <span class="keyword">in</span> new_xml_objects&#125;</span><br><span class="line">        old_data_list = <span class="built_in">set</span>(old_xml_objects_dict.keys())</span><br><span class="line">        new_data_list = <span class="built_in">set</span>(new_xml_objects_dict.keys())</span><br><span class="line">        add_list = <span class="built_in">list</span>(new_data_list.difference(old_data_list))</span><br><span class="line">        delete_list = <span class="built_in">list</span>(old_data_list.difference(new_data_list))</span><br><span class="line">        common_list = <span class="built_in">list</span>(old_data_list.intersection(new_data_list))</span><br><span class="line"></span><br><span class="line">        download_info = &#123;file_name: new_xml_objects_dict[file_name][<span class="string">&quot;FileSize&quot;</span>] <span class="keyword">for</span> file_name <span class="keyword">in</span> add_list&#125;</span><br><span class="line">        <span class="comment"># 根据每个文件的版本号，确定是否需要更新</span></span><br><span class="line">        <span class="keyword">for</span> file_name <span class="keyword">in</span> common_list:</span><br><span class="line">            <span class="keyword">if</span> <span class="built_in">int</span>(new_xml_objects_dict[file_name][<span class="string">&quot;Version&quot;</span>]) &amp;gt; <span class="built_in">int</span>(old_xml_objects_dict[file_name][<span class="string">&quot;Version&quot;</span>]):</span><br><span class="line">                download_info.update(&#123;file_name: new_xml_objects_dict[file_name][<span class="string">&quot;FileSize&quot;</span>]&#125;)</span><br><span class="line"></span><br><span class="line">        download_info_total.update(download_info)</span><br><span class="line">        delete_list_total.extend(delete_list)</span><br><span class="line">    <span class="comment"># return download_info, delete_list</span></span><br><span class="line">    <span class="keyword">return</span> download_info_total, delete_list_total</span><br></pre></td></tr></table></figure>
<h2 id="三、运行效果"><a href="#三、运行效果" class="headerlink" title="三、运行效果"></a>三、运行效果</h2><h3 id="1-程序目录结构"><a href="#1-程序目录结构" class="headerlink" title="1. 程序目录结构"></a>1. 程序目录结构</h3><p><strong>1.1 服务端</strong></p>
<p>ClientFolder目录用来存放要更新的文件夹，</p>
<p>venv是python目录，</p>
<p>cfg.ini文件用来配置ip、端口等信息，</p>
<p>server.py是主程序，</p>
<p>start.bat用来双击启动server.py，</p>
<p>VersionInfo.xml是存放文件信息的xml</p>
<p>       <img src="https://cdn.jsdelivr.net/gh/yushuaige/myblog@master/img/20200425213341739.png" alt="20200425213341739.png"></p>
<p><strong>1.2 客户端</strong></p>
<p>TempFolder目录用来存放下载下来的文件，</p>
<p>venv是python目录，</p>
<p>client.py是主程序，</p>
<p>start.bat用来双击启动server.py，</p>
<p>VersionInfo.xml是存放文件信息的xml，</p>
<p>VersionInfoTemp.xml是更新时自动生成的，是下载的最新配置文件</p>
<p>       <img src="https://cdn.jsdelivr.net/gh/yushuaige/myblog@master/img/20200425213310466.png" alt="20200425213310466.png"></p>
<h3 id="2-服务端运行效果"><a href="#2-服务端运行效果" class="headerlink" title="2. 服务端运行效果"></a>2. 服务端运行效果</h3><p>默认使用本地测试ip 127.0.0.1，默认端口8888</p>
<p>     <img src="https://cdn.jsdelivr.net/gh/yushuaige/myblog@master/img/20200425214624388.png" alt="20200425214624388.png"></p>
<h3 id="3-客户端运行效果"><a href="#3-客户端运行效果" class="headerlink" title="3. 客户端运行效果"></a>3. 客户端运行效果</h3><p>上面窗口是控制台窗口，显示运行过程的日志，下面是更新界面。</p>
<p>如果不想显示控制台界面，只需要把start.bat里前三行的注释打开即可。</p>
<p>文件太小可能会一闪而过，因为程序默认更新完立即退出。</p>
<p>    <img src="https://cdn.jsdelivr.net/gh/yushuaige/myblog@master/img/20200425215953325.png" alt="20200425215953325.png"></p>
<p>   <img src="https://cdn.jsdelivr.net/gh/yushuaige/myblog@master/img/20200425215030334.png" alt="20200425215030334.png"></p>
<h2 id="四、改进思路"><a href="#四、改进思路" class="headerlink" title="四、改进思路"></a>四、改进思路</h2><p><strong>1.多线程提高效率</strong></p>
<p>因为没有测试过文件数量和大小非常大的情况，现在程序的所有步骤都是单线程执行，可以将文件扫描和下载等耗时间的步骤，改进成多线程或者协程同时运行，提高程序的运行效率。</p>
<p><strong>2.文件扫描方式</strong></p>
<p>当前只根据文件相对路径加文件全名的方式，进行文件区分，然后根据最后修改时间来判断是否需要更新，可以增加MD5校验来保证文件的唯一性。</p>
<p><strong>3.界面完善</strong></p>
<p>当前只有在下载文件时有界面提示，可以改进界面，使整个更新过程可视化。</p>
<p><strong>4.启动方式</strong></p>
<p>当前使用bat脚本调命令行的方式启动程序，会有一个黑色窗口，可以将程序打包成exe文件发布。</p>
<h2 id="五、文件下载"><a href="#五、文件下载" class="headerlink" title="五、文件下载"></a>五、文件下载</h2><p>零积分下载整个程序源码：<a target="_blank" rel="noopener" href="https://download.csdn.net/download/yushuaigee/12362232">用Python实现一个软件自动升级系统</a></p>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          
          本博客所有文章除特别声明外，著作权归作者所有。转载请注明出处！
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://example.com/2020/04/25/%E7%94%A8Python%E5%AE%9E%E7%8E%B0%E4%B8%80%E4%B8%AA%E8%BD%AF%E4%BB%B6%E8%87%AA%E5%8A%A8%E5%8D%87%E7%BA%A7%E7%B3%BB%E7%BB%9F/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/python/" rel="tag">python</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/" rel="tag">程序设计</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2020/05/24/Golang%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%88%E4%B8%89%EF%BC%89%E2%80%94%E2%80%94%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            Golang学习笔记（三）——数据类型转换
          
        </div>
      </a>
    
    
      <a href="/2020/02/27/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E5%88%9D%E6%8E%A2%E2%80%94%E2%80%94%E5%85%AD%E5%A4%A7%E8%AE%BE%E8%AE%A1%E5%8E%9F%E5%88%99/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">设计模式初探——六大设计原则</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "zy6yBRj9KkWO2XxsT94n1DIW-gzGzoHsz",
    app_key: "auroBE2PQXkQ05CLi30SFv92",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
   
  
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2020-2021
        <i class="ri-heart-fill heart_icon"></i> 杰克小麻雀
      </li>
    </ul>
    <ul>
      <li>
        
        
        
        由 <a href="https://hexo.io" target="_blank">Hexo</a> 强力驱动
        <span class="division">|</span>
        主题 - <a href="https://github.com/Shen-Yu/hexo-theme-ayer" target="_blank">Ayer</a>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>访问人数:<span id="busuanzi_value_site_uv"></span></s>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>浏览次数:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/favicon.ico" alt="半亩方塘"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="搜索">
        <i class="ri-search-line"></i>
      </a>
      
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->


<script src="/js/clickBoom2.js"></script>


<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
  </div>
</body>
<script type="text/javascript">
if(!/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)){
  document.write('<script type="text/javascript" src="/js/FunnyTitle.js"><\/script>');
  document.write('<script type="text/javascript" src="/js/snow.js"><\/script>');
}
</script>
</html>